<?php

namespace app\extra\wx;

use Exception;
/*
 * 微信授权登录类
 */

class WxAuth
{
    public $app_id;
    public $app_secret;

    public function __construct($app_id, $app_secret)
    {
        $this->app_id     = $app_id;
        $this->app_secret = $app_secret;
    }

    /**
     * 重定向到授权地址
     * @param string $redirect_url
     * @param string $state
     * @param string $scope snsapi_userinfo|snsapi_base
     */
    public function auth($redirect_url, $scope = 'snsapi_userinfo', $state = 'STATE')
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->app_id&redirect_uri=$redirect_url&response_type=code&scope=$scope&state=$state#wechat_redirect";
        echo "<script>window.location.href='".$url."'</script>";
    }

    /**
     * 获取网页授权的AccessToken
     * @param $code
     * @return mixed
     * @throws Exception
     */
    public function getWebAccessToken($code)
    {
        $url    = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->app_id&secret=$this->app_secret&code=$code&grant_type=authorization_code";
        $result = json_decode($this->getData($url));

        // 异常处理
        if (isset($result->errcode)) throw new Exception($result->errmsg, 500);

        return $result;
    }

    /**
     * GET方式 请求数据
     * @param $url
     * @return bool|string
     */
    private function getData($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}